local skynet = require "skynet"
require "skynet.manager"
local skynetqueue = require "skynet.queue"

-- local is_test = skynet.getenv("is_test") == "true"
-- if is_test then
--     -- 测试环境下开启服务日志
--     function skynet.newservice(name, ...)
--         return skynet.call(".launcher", "lua" , "LOGLAUNCH", "snlua", name, ...)
--     end
-- end

-- 创建一个可热更服务
function skynet.new_hotservice(module_name, ...)
    return skynet.newservice("service/HotService", module_name, ...)
end

-- 热更新消息类型
skynet.PTYPE_HOTFIX = 13
skynet.PTYPE_GAME = 14
function skynet.dispatch_type(t, CMD, attrs)
    local ququeable = attrs and attrs.queue

    local queue
    if ququeable then
        -- 服务的消息队列
        queue = skynetqueue()
    end

    skynet.dispatch(t, function(session, source, cmd, ...)
        local f = CMD[cmd]
        if not f then
            GERRF("没有命令处理方法 service: %s, hot_script_name: %s, source: 0x%08x, self: 0x%08x, cmd: %s",
                SERVICE_NAME, HOT_SCRIPT_NAME, source, skynet.self(), cmd)
            return
        end

        if ququeable then
            if session ~= 0 then
                skynet.retpack(queue(f, ...))
            else
                queue(f, ...)
            end
            return
        end

        if session ~= 0 then
            skynet.retpack(f(...))
        else
            f(...)
        end
    end)
end

function skynet.dispatch_src_type(t, CMD)
    skynet.dispatch(t, function(session, source, cmd, ...)
        local f = CMD[cmd]
        if not f then
            GERRF("没有命令处理方法 source: %d, self: %s, cmd: %s", source, skynet.self(), cmd)
            return
        end

        if session ~= 0 then
            skynet.retpack(f(source, ...))
        else
            f(source, ...)
        end
    end)
end

function skynet.dispatch_lua_queue(CMD)
    skynet.dispatch_type("lua", CMD, {
        queue = true
    })
end

function skynet.dispatch_lua(CMD, attrs)
    skynet.dispatch_type("lua", CMD, attrs)
end

function skynet.dispatch_src_lua(CMD)
    skynet.dispatch_src_type("lua", CMD)
end

-- 获取配置并转换为 boolean 返回，没有配置或配置为 false 则返回 false
function skynet.getenvb(key, value)
    local value = skynet.getenv(key)
    if not value or value == "false" then
        return false
    end

    return true
end

-- 获取配置并转换为 number 返回，没有配置则返回 nil
function skynet.getenvn(key)
    local value = skynet.getenv(key)
    return value and tonumber(value)
end

-- 获取配置并转换为一个 table，没有配置则返回 nile
function skynet.getenvt(key)
    local value = skynet.getenv(key)
    return table.undump(value or "nil")
end
